package com.loong.config;

import com.loong.util.YamlReader;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class GenerateWords {
    public static void main(String[] args) {
        // 存放多个txt文件的目录，可根据实际情况修改
        YamlReader.loadResource("/application.yml");
        String sourceDirPath = (String) YamlReader.getValueByKey("words.dir");
        File sourceDir = new File(sourceDirPath);
        if (!sourceDir.exists() ||!sourceDir.isDirectory()) {
            System.out.println("源文件目录不存在或不是一个目录");
            return;
        }

        List<String> allWords = new ArrayList<>();

        // 遍历目录下的所有txt文件
        File[] txtFiles = sourceDir.listFiles((dir, name) -> name.endsWith(".txt"));
        if (txtFiles!= null) {
            for (File txtFile : txtFiles) {
                try (BufferedReader reader = new BufferedReader(new FileReader(txtFile))) {
                    String line;
                    while ((line = reader.readLine())!= null) {
                        allWords.add(line);
                    }
                } catch (IOException e) {
                    System.out.println("读取文件 " + txtFile.getAbsolutePath() + " 时出错: " + e.getMessage());
                }
            }
        }

        // 去重并排序
        List<String> uniqueAndSortedWords = allWords.stream()
                .distinct()
                .sorted(Comparator.naturalOrder())
                .collect(Collectors.toList());

        // 写入到目标文件words.txt，目标文件路径可根据实际情况修改
        String targetFilePath = (String) YamlReader.getValueByKey("words.outputDir");
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(targetFilePath))) {
            for (String word : uniqueAndSortedWords) {
                writer.write(word);
                writer.newLine();
            }
        } catch (IOException e) {
            System.out.println("写入文件 " + targetFilePath + " 时出错: " + e.getMessage());
        }

        System.out.println("处理完成，结果已写入words.txt文件");
    }
}
